// @see https://docs.aircode.io/guide/functions/
import {
    createTransport, Transporter, SentMessageInfo
} from 'nodemailer';
import { catchAwait } from "utils-lib-js"
type IMailOptions = {
    from: string
    to: string
    subject: string
    text: string
}
type IMailParams = { mail: string, title: string, content: string }

type IEnv = {
    service: string // 运营商 参考：node_modules\nodemailer\lib\well-known\services.json 中的配置
    host: string // 邮箱服务器地址
    port: number // 邮箱SSL协议端口号
    user: string //发送方的用户名，一般指邮箱号
    pass: string //发送方的密码，一般指专用密码或者邮箱授权码
    [key: string]: any
}
const { service, host, port, user, pass } = process.env as IEnv

const EmailTransporter = {
    service, // 运营商  qq 网易 若使用QQ邮箱，则只需配置service：qq
    host, // 若使用网易邮箱，则需配置host：smtp.163.com
    port, // 端口
    auth: {
        user, // 发送方的邮箱
        pass, // 发送方授权码
    },
};
class SendMail {
    transporter: Transporter<SentMessageInfo>
    mailOptions?: IMailOptions
    constructor() {
        this.transporter = createTransport(EmailTransporter); //邮箱配置项
    }
    /* 发送邮件模块
     * @method    sendEmail
     * @for       SendMail
     * @param   {String} mail  用户邮箱
     * @param   {String} title  邮件标题
     * @param   {String} content  邮件内容
     * @return {Promise<res>}   是否发送成功
     */
    sendEmail = (opts: IMailParams) => {
        const { mail, title, content } = opts
        this.mailOptions = {
            from: `消息来自 < ${user} >`,
            to: mail,
            subject: title,
            text: content,
        };
        return this.transporter.sendMail(this.mailOptions);
    };
}
const email = new SendMail();
export default async function (params: IMailParams, _: unknown) {
    console.log('Received params:', params);
    const [err, msg] = await catchAwait(email.sendEmail(params))
    return err ?? msg
}
